{% extends 'base.html' %}
{% load static %}

{% block title %}与 {{ other_user.nickname|default:other_user.username }} 的对话 - Meet活动聚{% endblock %}

{% block extra_css %}
<style>
    .message-container {
        height: 500px;
        overflow-y: auto;
        padding: 15px;
    }
    .message-bubble {
        max-width: 70%;
        padding: 10px 15px;
        border-radius: 18px;
        margin-bottom: 10px;
        position: relative;
    }
    .message-sent {
        background-color: #007bff;
        color: white;
        margin-left: auto;
        border-bottom-right-radius: 5px;
    }
    .message-received {
        background-color: #f1f1f1;
        color: #333;
        margin-right: auto;
        border-bottom-left-radius: 5px;
    }
    .message-time {
        font-size: 0.75rem;
        opacity: 0.7;
        margin-top: 5px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card shadow">
                <div class="card-header bg-primary text-white">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="d-flex align-items-center">
                            <a href="{% url 'social:message_list' %}" class="btn btn-sm btn-light me-2">
                                <i class="bi bi-arrow-left"></i>
                            </a>
                            {% if other_user.avatar %}
                            <img src="{{ other_user.avatar.url }}" class="rounded-circle me-2" width="40" height="40" alt="{{ other_user.username }}">
                            {% else %}
                            <i class="bi bi-person-circle me-2" style="font-size: 1.5rem;"></i>
                            {% endif %}
                            <h5 class="mb-0">{{ other_user.nickname|default:other_user.username }}</h5>
                        </div>
                        <a href="{% url 'users:user_profile' other_user.id %}" class="btn btn-sm btn-light">
                            <i class="bi bi-person"></i> 查看主页
                        </a>
                    </div>
                </div>
                
                <div class="card-body p-0">
                    <div class="message-container" id="message-container">
                        {% for message in messages %}
                        <div class="d-flex mb-3 {% if message.sender == user %}justify-content-end{% else %}justify-content-start{% endif %}">
                            {% if message.sender != user %}
                            <div class="d-flex align-items-start me-2">
                                {% if other_user.avatar %}
                                <img src="{{ other_user.avatar.url }}" class="rounded-circle" width="35" height="35" alt="{{ other_user.username }}">
                                {% else %}
                                <i class="bi bi-person-circle" style="font-size: 1.5rem;"></i>
                                {% endif %}
                            </div>
                            {% endif %}
                            
                            <div class="message-bubble {% if message.sender == user %}message-sent{% else %}message-received{% endif %}">
                                <div class="message-content">{{ message.content }}</div>
                                <div class="message-time text-end">
                                    {{ message.created_at|date:"H:i" }}
                                    {% if message.sender == user %}
                                        {% if message.is_read %}
                                        <i class="bi bi-check-all text-info"></i>
                                        {% else %}
                                        <i class="bi bi-check"></i>
                                        {% endif %}
                                    {% endif %}
                                </div>
                            </div>
                            
                            {% if message.sender == user %}
                            <div class="d-flex align-items-start ms-2">
                                {% if user.avatar %}
                                <img src="{{ user.avatar.url }}" class="rounded-circle" width="35" height="35" alt="{{ user.username }}">
                                {% else %}
                                <i class="bi bi-person-circle" style="font-size: 1.5rem;"></i>
                                {% endif %}
                            </div>
                            {% endif %}
                        </div>
                        {% empty %}
                        <div class="text-center py-5">
                            <i class="bi bi-chat-dots" style="font-size: 4rem; color: #6c757d;"></i>
                            <p class="mt-3 text-muted">还没有消息，开始对话吧！</p>
                        </div>
                        {% endfor %}
                    </div>
                    
                    <div class="card-footer">
                        <form id="message-form" class="d-flex">
                            {% csrf_token %}
                            <input type="hidden" name="receiver_id" value="{{ other_user.id }}">
                            <div class="flex-grow-1 me-2">
                                <input type="text" name="content" class="form-control" placeholder="输入消息..." required id="message-input">
                            </div>
                            <button type="submit" class="btn btn-primary" id="send-btn">
                                <i class="bi bi-send"></i> 发送
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 滚动到消息容器底部
    function scrollToBottom() {
        var container = $('#message-container');
        container.scrollTop(container[0].scrollHeight);
    }
    
    // 页面加载时滚动到底部
    scrollToBottom();
    
    // 发送消息
    $('#message-form').submit(function(e) {
        e.preventDefault();
        
        var content = $('#message-input').val().trim();
        if (!content) return;
        
        var $sendBtn = $('#send-btn');
        var originalText = $sendBtn.html();
        
        // 禁用发送按钮
        $sendBtn.prop('disabled', true).html('<i class="bi bi-hourglass-split"></i> 发送中...');
        
        $.ajax({
            url: '{% url "social:send_message" other_user.id %}',
            type: 'POST',
            data: {
                content: content,
                csrfmiddlewaretoken: '{{ csrf_token }}'
            },
            success: function(response) {
                if (response.success) {
                    // 清空输入框
                    $('#message-input').val('');
                    
                    // 添加新消息到界面
                    var messageHtml = `
                        <div class="d-flex mb-3 justify-content-end">
                            <div class="message-bubble message-sent">
                                <div class="message-content">${content}</div>
                                <div class="message-time text-end">
                                    ${new Date().toLocaleTimeString('zh-CN', {hour: '2-digit', minute:'2-digit'})}
                                    <i class="bi bi-check"></i>
                                </div>
                            </div>
                            <div class="d-flex align-items-start ms-2">
                                {% if user.avatar %}
                                <img src="{{ user.avatar.url }}" class="rounded-circle" width="35" height="35" alt="{{ user.username }}">
                                {% else %}
                                <i class="bi bi-person-circle" style="font-size: 1.5rem;"></i>
                                {% endif %}
                            </div>
                        </div>
                    `;
                    
                    $('#message-container').append(messageHtml);
                    scrollToBottom();
                } else {
                    alert('发送失败: ' + response.message);
                }
            },
            error: function() {
                alert('发送失败，请重试');
            },
            complete: function() {
                // 重新启用发送按钮
                $sendBtn.prop('disabled', false).html(originalText);
            }
        });
    });
    
    // 回车键发送消息
    $('#message-input').keypress(function(e) {
        if (e.which == 13 && !e.shiftKey) {
            e.preventDefault();
            $('#message-form').submit();
        }
    });
    
    // 自动刷新新消息（可选功能）
    function checkNewMessages() {
        // 这里可以添加轮询检查新消息的逻辑
        // 为了简化，暂时不实现
    }
    
    // 每10秒检查一次新消息
    // setInterval(checkNewMessages, 10000);
});
</script>
{% endblock %}